﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Tasks;

namespace ControlExplorer.Controls.Tile
{
    public partial class ListBoxSample : UserControl
    {
        public ListBoxSample()
        {
            TileCommand = new DelegateCommand<object>(ExecuteCommand, GetCanExecuteCommand);
            InitializeComponent();
            Loaded += new RoutedEventHandler(OnLoaded);
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            FlickrPhoto.Load("", listBox);
        }

        #region ** Command
        public DelegateCommand<object> TileCommand { get; set; }

        private void ExecuteCommand(object parameter)
        {
            // show tile content in the preview
            // ((FlickrPhoto)parameter).Content contains Image Uri
            NavigateUrl(((FlickrPhoto)parameter).Content);
        }

        public void NavigateUrl(string url)
        {
            try
            {
                var task = new WebBrowserTask();
                task.Uri = new Uri(url, UriKind.Absolute);
                task.Show();
            }
            catch { }
        }

        private bool GetCanExecuteCommand(object parameter)
        {
            return true;
        }
        #endregion

    }

    public class DelegateCommand<T> : ICommand
    {
        private static readonly Action<T> EmptyExecute = (T) => { };
        private static readonly Func<T, bool> EmptyCanExecute = (T) => true;


        private Action<T> _execute;
        private Func<T, bool> _canExecute;

        public DelegateCommand(Action<T> executeMethod)
            : this(executeMethod, null)
        {
        }

        public DelegateCommand(Action<T> execute, Func<T, bool> canExecute)
        {
            _execute = execute;
            _canExecute = canExecute;
        }

        public void Execute(T parameter)
        {
            _execute(parameter);
        }


        public bool CanExecute(T parameter)
        {
            return _canExecute(parameter);
        }


        bool ICommand.CanExecute(object parameter)
        {
            return this.CanExecute((T)parameter);
        }


        public event EventHandler CanExecuteChanged;
        public void RaiseCanExecuteChanged()
        {
            var h = this.CanExecuteChanged;
            if (h != null)
            {
                h(this, EventArgs.Empty);
            }
        }


        void ICommand.Execute(object parameter)
        {
            this.Execute((T)parameter);
        }
    }

}
